package com.acme.domain.bank;

public class CheckingAccount extends AbstractAccount{

	private double overdraft;
	private static final int DEFAULT_OVERDRAFT = 25;
	
	public CheckingAccount() {
		super();
		this.overdraft = DEFAULT_OVERDRAFT;
	}
	
	public CheckingAccount(double balance, double overdraft) throws IllegalArgumentException{
		super();
		if(balance<0 || overdraft<0)
			throw new IllegalArgumentException("balance or overdraft < 0");
		else{
			setBalance(balance);
			this.overdraft = overdraft;
		}
	}
	
	@Override
	public double maximumAmountToWithdraw() {
		return getBalance() + this.overdraft;
	}

	@Override
	public void deposit(double sum) {
		if(overdraft == DEFAULT_OVERDRAFT)
			super.deposit(sum);
		else if(sum > DEFAULT_OVERDRAFT - overdraft){
			sum -= (DEFAULT_OVERDRAFT - overdraft);
			overdraft = DEFAULT_OVERDRAFT;
			super.deposit(sum);
		}else
			overdraft += sum;
	}

	@Override
	public void withdraw(double sum) throws OverDraftLimitExceededException{
		if(getBalance() >= sum)
			setBalance(getBalance() - sum);
		else if(getBalance() + overdraft >= sum){
			sum -= getBalance();
			setBalance(0);
			overdraft -= sum;
		} else
			throw new OverDraftLimitExceededException(getBalance(), getBalance() + this.overdraft);
		assert allRight();
	}
	
	private boolean allRight(){
		if(getBalance()>=0 && this.overdraft>=0)
			return true;
		return false;
	}

	@Override
	public String toString() {
		return super.toString() + " overdraft = " + this.overdraft;
	}
	
}
